// review-magic.js - 记忆魔法屋页面
const storageManager = require('../../../manager/storageManager').getInstance();

Page({
  data: {
    reviewPlan: null, // 每日复习计划
    wordsForReview: [], // 需要复习的单词列表
    currentWordIndex: 0, // 当前单词索引
    currentWord: null, // 当前单词
    isLoading: true, // 加载状态
    reviewStats: {
      total: 0,
      reviewed: 0,
      mastered: 0,
      remaining: 0,
      breakdown: {
        easy: 0,
        normal: 0,
        hard: 0
      }
    },
    magicPower: 0, // 魔法能量（数值类型，用于计算）
    formattedMagicPower: '0.00', // 格式化的魔法能量（字符串类型，用于显示）
    completionBonus: 0, // 完成奖励
    suggestedTime: 0, // 建议复习时间
    isReviewing: false, // 是否正在复习
    reviewStartTime: null, // 复习开始时间
    showReviewComplete: false, // 是否显示复习完成界面
    reviewTime: 0, // 复习用时（秒）
    animationData: {}, // 动画数据
    showDifficultyRating: false, // 是否显示复习操作按钮
    selectedDifficulty: 'normal', // 选择的难度级别
    // 发音设置
    pronunciationType: 'american',
    playbackSpeed: 1.0,
    autoPlay: false,
    isPlaying: false
  },

  onLoad: function() {
    // 获取全局应用实例
    this.app = getApp();
    
    // 初始化数据管理器和复习计划器
    this.wordDataManager = this.app.globalData.wordDataManager;
    this.reviewScheduler = this.app.getReviewScheduler();
    
    // 初始化音频管理器
    this.initAudioManager();
    
    // 加载发音设置
    this.loadPronunciationSettings();
    
    // 加载复习计划
    this.loadReviewPlan();
  },
  
  /**
   * 初始化音频管理器
   */
  initAudioManager: function() {
    if (!this.audioManager) {
      try {
        // 获取全局AudioManager实例
        this.audioManager = this.app.getAudioManager();
        this.audioManager.addStatusChangeCallback(this.onAudioStatusChange.bind(this));
      } catch (error) {
        console.warn('音频管理器加载失败:', error);
      }
    }
  },
  
  /**
   * 音频状态变化回调函数
   */
  onAudioStatusChange: function(status) {
    this.setData({
      isPlaying: status.isPlaying
    });
  },
  
  /**
   * 加载发音设置
   */
  loadPronunciationSettings: function() {
    try {
      const pronunciationType = this.wordDataManager.getPronunciationType();
      const playbackSpeed = this.wordDataManager.getPlaybackSpeed();
      const autoPlay = this.wordDataManager.getAutoPlay();

      this.setData({
        pronunciationType: pronunciationType || 'american',
        playbackSpeed: playbackSpeed || 1.0,
        autoPlay: autoPlay || false
      });
    } catch (error) {
      console.error('加载发音设置失败:', error);
    }
  },

  onShow: function() {
    // 如果页面重新显示，重新加载数据
    if (this.data.isLoading) {
      this.loadReviewPlan();
    }
  },
  
  onUnload: function() {
    // 移除音频状态变化回调
    if (this.audioManager) {
      this.audioManager.removeStatusChangeCallback(this.onAudioStatusChange.bind(this));
    }
  },

  // 加载复习计划
  loadReviewPlan: function() {
    this.setData({ isLoading: true });
    
    try {
      // 生成每日复习计划
      const reviewPlan = this.reviewScheduler.generateDailyReviewPlan();
      const wordsForReview = reviewPlan.words;
      const totalCount = reviewPlan.totalCount;
      
      // 生成复习统计数据
      const reviewStats = {
        total: totalCount,
        reviewed: 0,
        mastered: 0,
        remaining: totalCount,
        breakdown: reviewPlan.breakdown || { easy: 0, normal: 0, hard: 0 }
      };
      
      // 创建动画效果
      const animation = wx.createAnimation({
        duration: 1000,
        timingFunction: 'ease',
      });
      
      // 保留原始数值用于计算，格式化后的值用于显示
      const magicPowerValue = parseFloat(reviewPlan.magicPower || 0);
      const formattedMagicPower = magicPowerValue.toFixed(2);
      
      this.setData({
        reviewPlan,
        wordsForReview,
        reviewStats,
        magicPower: magicPowerValue,
        formattedMagicPower: formattedMagicPower,
        completionBonus: reviewPlan.completionBonus || 0,
        suggestedTime: reviewPlan.suggestedTime || 5,
        currentWordIndex: 0,
        currentWord: totalCount > 0 ? wordsForReview[0] : null,
        isLoading: false,
        animationData: animation.export()
      });
      
      // 启动魔法能量动画
      this._startMagicPowerAnimation();
    } catch (error) {
      console.error('加载复习计划失败:', error);
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
      this.setData({ isLoading: false });
    }
  },
  
  // 启动魔法能量动画
  _startMagicPowerAnimation: function() {
    const animation = wx.createAnimation({
      duration: 1500,
      timingFunction: 'ease-in-out',
    });
    
    animation.opacity(1).translateY(0).step();
    this.setData({
      animationData: animation.export()
    });
  },

  // 开始复习
  startReview: function() {
    if (this.data.wordsForReview.length === 0) {
      wx.showToast({
        title: '没有需要复习的单词',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      isReviewing: true,
      reviewStartTime: new Date().getTime(),
      showDifficultyRating: false, // 先显示难度选择
      selectedDifficulty: 'normal'
    });
  },
  
  // 显示复习操作按钮（选择难度后）
  showReviewActions: function(e) {
    const difficulty = e.detail.difficulty;
    this.setData({
      showDifficultyRating: true,
      selectedDifficulty: difficulty
    });
  },

  // 标记单词复习结果
  markReviewResult: function(e) {
    console.log('markReviewResult event detail:', e.detail);
    
    try {
      // 记录复习结果
      // 确保 isRemembered 是布尔值
      const isRemembered = typeof e.detail.isRemembered === 'string' 
        ? e.detail.isRemembered === 'true' 
        : Boolean(e.detail.isRemembered);
      
      this.reviewScheduler.recordReviewResult(
        e.detail.wordId,
        isRemembered,
        e.detail.difficulty || 'normal'
      );
      
      // 播放操作反馈动画
      const animation = wx.createAnimation({
        duration: 300,
        timingFunction: 'ease',
      });
      
      animation.scale(1.1).opacity(0.8).step().scale(1).opacity(1).step();
      this.setData({ animationData: animation.export() });
      
      // 更新复习统计
      const reviewStats = {
        ...this.data.reviewStats,
        reviewed: this.data.reviewStats.reviewed + 1,
        mastered: isRemembered ? this.data.reviewStats.mastered + 1 : this.data.reviewStats.mastered,
        remaining: this.data.reviewStats.remaining - 1
      };
      
      // 移动到下一个单词
      const currentWordIndex = this.data.currentWordIndex + 1;
      
      if (currentWordIndex < this.data.wordsForReview.length) {
        this.setData({
          currentWordIndex,
          currentWord: this.data.wordsForReview[currentWordIndex],
          reviewStats,
          showDifficultyRating: false, // 重置为显示难度选择
          selectedDifficulty: 'normal'
        });
      } else {
        // 复习完成
        const reviewTime = Math.floor((new Date().getTime() - this.data.reviewStartTime) / 1000);
        
        this.setData({
          reviewStats,
          isReviewing: false,
          showReviewComplete: true,
          reviewTime
        });
        
        // 更新首页的复习数量
      const quickReviewComponent = getApp().globalData.quickReviewComponent;
      if (quickReviewComponent) {
        quickReviewComponent.loadReviewCount();
      }
      
      // 更新今日复习单词任务数据
      this._updateTodayTaskData('review', this.data.wordsForReview[currentWordIndex - 1]);
      }
    } catch (error) {
      console.error('记录复习结果失败:', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
  },

  // 播放单词发音
  playPronunciation: function(e) {
    console.log(e)
    const currentWord = e.detail.word;

    if (!currentWord) {
      wx.showToast({
        title: '当前没有单词可播放',
        icon: 'none'
      });
      return;
    }

    // 初始化音频管理器
    this.initAudioManager();

    // 现在直接传入单词对象，让audioManager内部处理音频URL获取和错误处理
    this.audioManager.playPronunciation(currentWord, this.data.playbackSpeed, this.data.pronunciationType)
      .then(() => {
        this.updateAudioStatus();
      })
      .catch(error => {
        console.error('播放失败:', error);
        wx.showToast({
          title: '播放失败',
          icon: 'none'
        });
        this.updateAudioStatus();
      });
  },
  
  /**
   * 停止发音播放
   */
  stopPronunciation: function() {
    this.initAudioManager();
    this.audioManager.stopPronunciation();
    this.updateAudioStatus();
  },
  
  /**
   * 更新音频状态到UI
   */
  updateAudioStatus: function() {
    const status = this.audioManager.getStatus();
    this.setData({
      isPlaying: status.isPlaying
    });
  },

  // 再复习一次
  reviewAgain: function() {
    this.loadReviewPlan();
    this.setData({
      showReviewComplete: false,
      showDifficultyRating: false,
      selectedDifficulty: 'normal'
    });
  },

  // 返回词书页面
goWordbook: function() {
  wx.switchTab({
    url: '/pages/vocabulary/wordbook/wordbook'
  });
},

  // 开始限时挑战
  startTimedChallenge: function() {
    wx.navigateTo({
      url: '/pages/challenge/timed-challenge/timed-challenge?source=review_magic'
    });
  },
  
  /**
   * 更新今日任务数据
   * @param {string} taskType - 任务类型 ('new' 或 'review')
   * @param {Object} word - 完成复习的单词
   */
  _updateTodayTaskData: function(taskType, word) {
    try {
      // 获取当前词书信息
      const currentBook = this.wordDataManager.getCurrentBook && this.wordDataManager.getCurrentBook() || null;
      if (!currentBook) {
        console.warn('未找到当前词书信息');
        return;
      }
      
      // 获取今日任务组件实例
      const app = getApp();
      if (app.globalData.todayTasksComponent && app.globalData.todayTasksComponent.refreshTasks) {
        // 刷新今日任务数据
        app.globalData.todayTasksComponent.refreshTasks();
      } else {
        console.log('今日任务组件未初始化，稍后会自动更新');
        // 记录学习事件到本地存储，方便任务组件加载时识别
        const learningEvents = storageManager.getStorage(storageManager.STORAGE_KEYS.TODAY_LEARNING_EVENTS) || [];
        
        learningEvents.push({
          type: taskType,
          bookId: currentBook.id,
          wordId: word.id,
          timestamp: new Date().toISOString()
        });
        
        storageManager.setStorage(storageManager.STORAGE_KEYS.TODAY_LEARNING_EVENTS, learningEvents);
      }
    } catch (error) {
      console.error('更新今日任务数据失败:', error);
    }
  },

  // 下拉刷新
  onPullDownRefresh: function() {
    this.loadReviewPlan();
    wx.stopPullDownRefresh();
  },

  // 分享页面
  onShareAppMessage: function() {
    return {
      title: '记忆魔法屋 - 巩固你的单词记忆！',
      path: '/pages/vocabulary/review-magic/review-magic',
      // imageUrl: '/images/book.png'
    };
  }
});